package io.renren.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.IntDexUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.dao.RoomEslDao;
import io.renren.dao.SeatEslDao;
import io.renren.entity.*;
import io.renren.param.EslHeartBeatParam;
import io.renren.param.RefreshEslParam;
import io.renren.param.SetContentParam;
import io.renren.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.*;


/**
 * 电子价签
 *
 * @author 1
 * @email 1@2.com
 * @date 2021-09-17 15:57:01
 */
@RestController
@RequestMapping("/esl")
@Slf4j
public class EslController {

    @Autowired
    private EslService eslService;

    @Autowired
    private EslContentService eslContentService;

    @Autowired
    private EslWorkingService eslWorkingService;

    @Autowired
    private RoomEslService roomEslService;

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private ApService apService;

    @Autowired
    private RoomEslDao roomEslDao;

    @Autowired
    private SeatEslDao seatEslDao;

    @Autowired
    private SeatApplicationService seatApplicationService;

    @Autowired
    private SeatEslService seatEslService;

    /**
     * 列表，返回未绑定用户的ap
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {

        if (StringUtils.isNotBlank((String) params.get("eslId"))) {
            params.put("eslId", IntDexUtils.DtoH(new BigInteger((String) params.get("eslId"))));
//            params.put("eslId", IntDexUtils.DtoH1(Integer.valueOf((String) params.get("eslId"))));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("ip", (String) params.get("apIP"));
        PageUtils apPage = apService.queryPage(map);
        List<ApEntity> apEntities = (List<ApEntity>) apPage.getList();

        // hanshow有1489片esl，前端无法显示这么多，先写死要用的
        if ("wpE44jCAAAqhmHGQv5jB4wS7GnEasD1Q".equals(params.get("compId"))) {
            List<String> esls = new ArrayList<>();
            esls.add("1473703820");
            esls.add("1453597637");
            esls.add("1453589701");
            esls.add("1453589445");
            esls.add("1452506053");
            esls.add("1453557957");
            esls.add("1453574853");

            List<String> eslIds = new ArrayList<>();
            for (String esl : esls) {
                eslIds.add(IntDexUtils.DtoH(new BigInteger(esl)));
            }

            params.put("eslIds", eslIds);
        }
        PageUtils page = null;
        if (CollectionUtil.isNotEmpty(apEntities)) {
            params.put("apId", apEntities.get(0).getApId());
            page = eslService.queryPage(params);
            List<EslEntity> eslEntities = (List<EslEntity>) page.getList();
            for (EslEntity eslEntity : eslEntities) {
                eslEntity.setEslId(String.valueOf(IntDexUtils.HtoD(eslEntity.getEslId())));
            }
        }

        //剔除已经绑定的esl
        List<EslEntity> eslEntities = (List<EslEntity>) page.getList();
        List<RoomEslEntity> roomEslEntities = roomEslDao.selectList(new QueryWrapper<RoomEslEntity>());
        List<SeatEslEntity> seatEslEntities = seatEslDao.selectList(new QueryWrapper<SeatEslEntity>());
        for (RoomEslEntity roomEslEntity : roomEslEntities) {
            remove(eslEntities, String.valueOf(IntDexUtils.HtoD(roomEslEntity.getEslId())));
        }
        for (SeatEslEntity seatEslEntity : seatEslEntities) {
            remove(eslEntities, String.valueOf(IntDexUtils.HtoD(seatEslEntity.getEslId())));
        }

        page.setList(eslEntities);


        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        EslEntity esl = eslService.getById(id);

        return R.ok().put("esl", esl);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody EslHeartBeatParam param) {
        eslService.batchSave(param);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody EslEntity esl) {
        ValidatorUtils.validateEntity(esl);
        eslService.updateById(esl);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        eslService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 设置铭牌
     */
    @PostMapping("/setContent")
    public R setContent(@RequestBody SetContentParam param) {
        ValidatorUtils.validateEntity(param);
        List<SetContentParam> params = new ArrayList<>();
        params.add(param);

        eslContentService.setContent(params);

        return R.ok();
    }

    /**
     * 刷新铭牌
     */
    @PostMapping("/refreshNamePlate")
    public R refreshNamePlate(@RequestBody RefreshEslParam param) {
//        ValidatorUtils.validateEntity(param);

        ApplicationEntity applicationEntity = applicationService.getById(param.getApplicationId());

        if (!param.getUserId().equals(applicationEntity.getEmployeeId())) {
            throw new RRException("会议预约人才能刷新铭牌");
        }

        eslContentService.refreshNamePlate(param.getApplicationId());

        return R.ok();
    }

    /**
     * 刷新门牌
     */
    @PostMapping("/refreshDoorPlate")
    public R refreshDoorPlate(@RequestBody RefreshEslParam param) {
        ValidatorUtils.validateEntity(param);

        // 查询当前时间是否有会议进行中，如有，不允许刷新铭牌
        List<ApplicationEntity> applicationEntities = applicationService.queryUnfinish(Long.valueOf(param.getRoomId()));

        if (CollectionUtil.isEmpty(applicationEntities)) {
            throw new RRException("该会议室没有未结束的会议，不能刷新铭牌");
        }

        List<RoomEslEntity> roomEslEntitys = roomEslService.queryByRoomIdAndType(Convert.toLong(param.getRoomId()), "door");

        eslContentService.refreshDoorPlate(applicationEntities.get(0), roomEslEntitys.get(0));

        return R.ok();
    }

    /**
     * 获取铭牌内容
     */
    @RequestMapping("/getContent")
    public R getContent(@RequestParam Map<String, Object> params) {

        PageUtils page = eslContentService.queryPage(params);

        return R.ok().put("page", page);
    }

    public static void remove(List<EslEntity> list, String target) {
        Iterator<EslEntity> iter = list.iterator();
        while (iter.hasNext()) {
            String item = iter.next().getEslId();
            if (item.equals(target)) {
                iter.remove();
            }
        }
    }

    /**
     * 刷新工位
     */
    @PostMapping("/refreshSeatPlate")
    public R refreshSeatPlate(@RequestBody RefreshEslParam param) {
        ValidatorUtils.validateEntity(param);

        List<SeatApplicationEntity> applicationEntitys = seatApplicationService.queryByCompId(param.getCompId());

        if (CollectionUtil.isEmpty(applicationEntitys)) {
            log.debug("公司[{}]没有工位预约记录，退出", param.getCompId());
            return R.error("没有工位预约记录");
        }

        for (SeatApplicationEntity applicationEntity : applicationEntitys) {
            SeatEslEntity seatEslEntity = seatEslService.queryBySeatId(applicationEntity.getSeatId());
            if (seatEslEntity == null || seatEslEntity.getEslId() == null) {
                log.warn("工位id" + applicationEntity.getSeatId() + "未绑定铭牌");
            }

            //刷新工位铭牌
            eslContentService.refreshSeatPlate(applicationEntity, seatEslEntity);
        }

        return R.ok();
    }

}
